package com.fjwt.gz.service.activity.platform.acte025;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.AwardCouponDTO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.db.entity.AgentInfoEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.ActivityAwardService;
import com.fjwt.gz.service.impl.ActivityService;
import com.fjwt.gz.service.impl.ActivitySettingService;
import com.fjwt.gz.service.impl.AgentInfoService;
import com.fjwt.gz.service.impl.AwardCouponService;
import com.fjwt.gz.service.impl.AwardSettingService;
import com.fjwt.gz.service.impl.FansAwardService;
import com.fjwt.gz.service.impl.SendAwardService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 定向派券活动------
 */
@Slf4j
@Service
public class ACTE025Service extends BaseActivityService<Object> {

    private static String logPrefix = "【会员福利活动】";
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private FansAwardService fansAwardService;
    @Autowired
    private SendAwardService sendAwardService;
    @Autowired
    private AwardCouponService couponAwardService;
    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private AwardSettingService awardSettingService;

    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE025的活动");
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("更新ACTE025的活动");
        super.update(activityDTO);
    }

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE025的活动");
        super.delete(activityId);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE025的活动详情");
        BaseActivityDTO baseActivityDetailsVO = super.detail(activityId);
        return baseActivityDetailsVO;
    }


    /**
     * 兑换奖品
     */
   @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("进入{}", logPrefix);
        super.takePartIn(fansActivityDTO);

        log.info("用户基本信息：{}", JSONUtil.toJsonStr(fansEntity));

        // 校验活动限制
       JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

       // 获取活动奖品
       List<ActivityAwardAndSettingBo> activityAwardList = awardSettingService.getActivityAwardList(fansActivityDTO.getActivityId(), redisOutTime);

       // 校验用户奖品限制
       Map<Long, JSONObject> awardUserTimesJsonMap = new HashMap<>();
       for (ActivityAwardAndSettingBo activityAwardAndSettingBo : activityAwardList) {
           JSONObject awardUserTimesJson = awardSettingService.AwardSettingRule(fansEntity.getFansId(), activityEntity.getAgentNo(), activityAwardAndSettingBo);
           if (ObjectUtils.isNotEmpty(awardUserTimesJson)) {
               awardUserTimesJsonMap.put(activityAwardAndSettingBo.getAwardId(), awardUserTimesJson);
           }
       }

       for (ActivityAwardAndSettingBo activityAwardAndSettingBo : activityAwardList) {
           Long fansAwardId = sendAwardService.sendCouponOrGoods(fansActivityDTO.getFansId(), fansActivityDTO.getAppId(), activityAwardAndSettingBo, activityEntity.getPayAuthId(), null, true,
                   fansActivityDTO.getExtJson());
           JSONObject awardUserTimesJson = awardUserTimesJsonMap.get(activityAwardAndSettingBo.getAwardId());
           //更新Redis中参与的次数
           awardSettingService.updateAwardLimitCache(awardUserTimesJson, redisOutTime);

           if (StringUtils.isNotEmpty(fansActivityDTO.getAgentNo()) && null != fansAwardId) {
               AgentInfoEntity agentInfo = agentInfoService.getById(fansActivityDTO.getAgentNo());
               if (null != agentInfo) {
                   FansAwardEntity awardEntity = new FansAwardEntity();
                   awardEntity.setFansAwardId(fansAwardId);
                   awardEntity.setSendAgentNo(agentInfo.getAgentNo());
                   awardEntity.setSendAgentNo1(agentInfo.getAgentNo1());
                   awardEntity.setSendAgentNo2(agentInfo.getAgentNo2());
                   awardEntity.setSendAgentNo3(agentInfo.getAgentNo3());
                   awardEntity.setSendAgentNo4(agentInfo.getAgentNo4());
                   fansAwardService.updateById(awardEntity);
               }
           }
       }

       //重新放置活动奖品配置缓存
       if (!activityAwardList.isEmpty()) {
           String activityAwardKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, fansActivityDTO.getActivityId(), Constants.REDIS_ACTIVITY.AWARD);
           RedisUtil.set(activityAwardKey, activityAwardList, redisOutTime, TimeUnit.MILLISECONDS);
           log.info("活动奖品列表，修改奖品中的当前周期性领取次数数据，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(activityAwardList), redisOutTime, "TimeUnit.MILLISECONDS");
       }

       //更新Redis中参与的次数
       ActivityUserTimesBO activityUserTimesBO = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
       if (ObjectUtils.isNotEmpty(activityUserTimesBO)){
           activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
       }
       Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
       if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
           RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
       }

       return activityAwardService.toUserData(null);
    }


    /**
     * 每日或卡券查询
     */

    public List<AwardCouponDTO> selectProcess() {
        LambdaQueryWrapper<ActivityEntity> activityWrapper = new LambdaQueryWrapper<>();
        activityWrapper.eq(ActivityEntity::getActivityTemplateNo, "ACTE025");
        List<AwardCouponDTO> couponAwardList = new ArrayList<>();
        List<ActivityEntity> activityList = activityService.list(activityWrapper);
        for (ActivityEntity activityEntity : activityList){
            List<AwardCouponDTO> list = couponAwardService.selectProcess(activityEntity.getActivityId());
            for (AwardCouponDTO couponAward : list){
                couponAward.setNumberSheets(couponAward.getPeriodTimes()-couponAward.getCurrentPeriodTimes());
                couponAwardList.add(couponAward);
            }
        }
        return couponAwardList;
    }
}
